package com.netintech.project.system.controller;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.ImmutableMap;
import com.netintech.common.constant.Page;
import com.netintech.project.system.domain.SysMenu;
import com.netintech.project.system.domain.dto.CommonsDto;
import com.netintech.project.system.domain.dto.RoleDTO;
import com.netintech.project.system.service.SysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.netintech.common.constant.UserConstants;
import com.netintech.common.utils.SecurityUtils;
import com.netintech.common.utils.poi.ExcelUtil;
import com.netintech.core.aspectj.lang.annotation.Log;
import com.netintech.core.aspectj.lang.enums.BusinessType;
import com.netintech.core.web.controller.BaseController;
import com.netintech.core.web.domain.RequestResult;
import com.netintech.core.web.page.TableDataInfo;
import com.netintech.project.system.domain.SysRole;
import com.netintech.project.system.service.SysRoleService;

import javax.validation.Valid;

/**
 * 角色信息
 *
 * @author admin
 */
@Slf4j
@RestController
@RequestMapping("system/role")
public class SysRoleController extends BaseController {
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysMenuService sysMenuService;
//
//    @PreAuthorize("@ss.hasPermi('system:role:list')")
//    @GetMapping("/index")
//    public TableDataInfo list(SysRole role) {
//        setPageParam();
//        List<SysRole> list = roleService.selectRoleList(role);
//        return getDataTable(list);
//    }

    /**
     * “角色管理” 页面
     *
     * @return
     */
    @PostMapping("index")
    public RequestResult role(@RequestBody RoleDTO roleDTO) {
        Map<String, Object> result = new HashedMap();
        roleDTO.setPageNum(roleDTO.getPageNum() == null ? 1 : roleDTO.getPageNum());
        roleDTO.setPageSize(roleDTO.getPageSize() == null ? Page.pageSize : roleDTO.getPageSize());
        PageHelper.startPage(roleDTO.getPageNum(), roleDTO.getPageSize());
        List<SysRole> roles = roleService.selAllByCondition(roleDTO);
        PageInfo<SysRole> pageInfo = new PageInfo<>(roles, roleDTO.getPageSize());
        result.put("pageInfo", pageInfo);
        return RequestResult.success(result);
    }


    /**
     * 新增角色页面
     *
     * @return
     */
    @PostMapping("toAdd")
    public RequestResult toAddUser() {
        List<SysMenu> resources = sysMenuService.selectAll();
//        List<ImmutableMap<Object, Object>> resourceAll = resources.stream().map(resource -> ImmutableMap.builder().
//                put("id", resource.getMenuId()).put("name", resource.getMenuName())
//                .put("children",resource.getChildren())
//                .build()).collect(Collectors.toList());
//        所有的资源
        return RequestResult.success(ImmutableMap.builder().put("resourceAll", resources).build());
    }


    /**
     * 修改角色页面
     *
     * @return
     */
    @PostMapping("toUpd")
    public RequestResult toUpdRole(@RequestBody CommonsDto commonsDto) {
        Map<String, Object> result = new HashedMap();
        Long id = commonsDto.getId();
        SysRole role = roleService.selectRoleById(id);
        //        查出角色下面的资源id
        List<Long> menuIds = sysMenuService.selMenuIdsByRoleId(id);
//        查出有子节点的资源
        List<Long> hasChild = sysMenuService.queryHasChild();
        menuIds.removeAll(hasChild);
        role.setMenuIds(menuIds.toArray(new Long[0]));
        result.put("role", role);
        List<SysMenu> resources = sysMenuService.selectAll();
        result.put("resourceAll", resources);
        return RequestResult.success(result);
    }

    /**
     * 新增角色
     *
     * @return
     */
    @PostMapping("add")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    public RequestResult addUser(@Valid @RequestBody SysRole role) {
        role.setStatus("0");
        role.setCreateBy(SecurityUtils.getUsername());
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return RequestResult.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return RequestResult.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        return returnResult(roleService.insertRole(role));
    }

    /**
     * 修改角色
     *
     * @return
     */
    @PostMapping("upd")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    public RequestResult edit(@Valid @RequestBody SysRole role) {
//        roleService.checkRoleAllowed(role);
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return RequestResult.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return RequestResult.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(SecurityUtils.getUsername());
        return returnResult(roleService.updateRole(role));
    }

    /**
     * 删除角色
     *
     * @return
     */
    @PostMapping("delete")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    public RequestResult deleteById(@RequestBody CommonsDto commonsDto) {
        return returnResult(roleService.deleteRoleById(commonsDto.getId()));
    }


    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:role:export')")
    @GetMapping("/export")
    public RequestResult export(SysRole role) {
        List<SysRole> list = roleService.selectRoleList(role);
        ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
        return util.exportExcel(list, "角色数据");
    }

    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public RequestResult getInfo(@PathVariable Long roleId) {
        return RequestResult.success(roleService.selectRoleById(roleId));
    }


    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public RequestResult dataScope(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        return returnResult(roleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public RequestResult changeStatus(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        role.setUpdateBy(SecurityUtils.getUserIdString());
        return returnResult(roleService.updateRoleStatus(role));
    }

    /**
     * 删除角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public RequestResult remove(@PathVariable Long[] roleIds) {
        return returnResult(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    public RequestResult optionselect() {
        return RequestResult.success(roleService.selectRoleAll());
    }
}